#!/bin/sh
#
# Make a zip package signed for distribution
#

echo "DEFY ADDONS PACKAGER: $1"
echo "-------------------------------------------------"

DEVICE_OUT=$ANDROID_BUILD_TOP/out/target/product/mb525
DEVICE_TOP=$ANDROID_BUILD_TOP/device/moto/mb525
VENDOR_TOP=$ANDROID_BUILD_TOP/vendor/motorola/jordan

OUT_TARGET_HOST=`uname -a | grep Darwin`
if [ -z "$OUT_TARGET_HOST" ]
then
	OUT_TARGET_HOST=linux-x86
	MD5=md5sum
	XARGS="xargs --max-args=1 --max-procs `grep 'processor' /proc/cpuinfo|wc -l`"
	SED=sed
else
	OUT_TARGET_HOST=darwin-x86
	MD5=md5
	XARGS="xargs -n 1 -P `sysctl hw.ncpu | awk '{print $2}'`"
	SED=gsed
fi

if [ -z "$OUT" -o ! -d "$OUT" ]; then
	echo "ERROR: $0 only works with a full build environment. $OUT should exist."
	exit 1
fi

REPACK=$OUT/repack.d
echo "Sanitizing environment..."
rm -rf $REPACK

# We need an otapackage to grab the updater-binary
if [ "$TARGET_BUILD_TYPE" = "debug" ]; then
	OTAPACKAGE=$OUT/${TARGET_PRODUCT}_debug-ota-$TARGET_BUILD_VARIANT.$USER.zip
elif [ "$TARGET_BUILD_VARIANT" = "userdebug" ]; then
	OTAPACKAGE=$OUT/${TARGET_PRODUCT}-ota-eng.$USER.zip
else
	OTAPACKAGE=$OUT/${TARGET_PRODUCT}-ota-$TARGET_BUILD_VARIANT.$USER.zip
fi
if [ ! -f "$OTAPACKAGE" ]; then
	echo "$OTAPACKAGE doesn't exist!"
	exit 1
fi

# Unpack the otapackage and opticharge all apks
mkdir -p $REPACK/ota

echo "Unpacking $OTAPACKAGE..."
cd $REPACK/ota
#only keep kernel modules and signatures
unzip -q $OTAPACKAGE "system/lib/modules/*" "META-INF/*"

# Default package name for the new signed package
OUTFILE=$OUT/addons.zip

# Include device specific script
if [ -f $DEVICE_TOP/releasetools/addons.sh ]; then
	. $DEVICE_TOP/releasetools/addons.sh
fi

# Optimize apks
if [ -d $REPACK/ota/system/app ]; then
	cd $REPACK/ota/system/app
	find ./ -name \*.apk | $XARGS $OPTICHARGER
fi

# Strip modules
[ -d $REPACK/ota/system/lib/modules ] && \
	find $REPACK/ota/system/lib/modules -name "*.ko" -not -name "overclock*" -print0 | xargs -0 arm-eabi-strip --strip-unneeded

# Pack it up and sign
echo "Zipping package..."
( cd $REPACK/ota; zip $QUIET -r $REPACK/update.zip . )
echo
echo "Signing package..."
SECURITYDIR=$ANDROID_BUILD_TOP/build/target/product/security
java -Xmx768m \
	-jar $ANDROID_BUILD_TOP/out/host/$OUT_TARGET_HOST/framework/signapk.jar \
	-w $SECURITYDIR/testkey.x509.pem $SECURITYDIR/testkey.pk8 \
	$REPACK/update.zip $OUTFILE
rm -rf $REPACK
echo

echo "Addon package complete: $OUTFILE"
echo
ls -l $OUTFILE

exit 0
